﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Magic.Framework.OQL;
using Antlr.Runtime;
using System.Diagnostics;
using Ddbs.QE.Parser.Front;
using Ddbs.QE.Parser.Front.Serialization;
using Ddbs.QE.Message;

namespace QueryHandler
{
    public class QueryProcessor
    {

        public static Conf conf;
        public static ConfHelper confHelper;

        public static List<QEMessage> Handle(string input, string sitename, ref string treeStr)
        {

            //List<QEMessage> messageList = new List<QEMessage>();
 
            SQLLexer lex = new SQLLexer(new CaseInsensitiveStringStream(input));
            CommonTokenStream tokens = new CommonTokenStream(lex);
            SQLParser parser = new SQLParser(tokens);
            SQLParser.start_return statements = parser.start();

            List<SQLContext> contexts = SQLParserHeler.extractSQLContexts(statements);
            foreach (SQLContext context in contexts)
            {
                if (context.Columns == null || context.Tables == null) 
                {
                    throw new Exception("can't determine Columns or Tables!");
                }
                //SQLParserHeler.printContext(context);
                if (!Ddbs.QE.Parser.Front.Factory.SQLSemanticer.check(context, conf))
                {
                    throw new Exception("semantic check fail!");
                }
                AlgebraTree tree = new AlgebraTree(context);
                treeStr = tree.ToString();
                return tree.buildMessages(sitename);

            }
            throw new Exception("semantic check fail!");
        }

    }
}
